#! /usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json

import FileHostProtoType


class ifiitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class ifileit(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "iFile.it" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'
        self.apikey = ''

            
    def login(self):
        if self.islogin:
            return True
        #build opener
        self.generateOpener()
        self.fherr.write('login to iFile.it %s/%s...'%(self._user,'*'*len(self._pwd)))
        loginData = {'username' : self._user, \
                'password' : self._pwd}
        response = self.loginFileHost("https://secure.filecloud.io/api-fetch_apikey.api", loginData)
        
        content = json.loads(response)
        if not content['status'] == 'ok':
            self.fherr.write("User %s Failed to Login DepositFiles." % self._user)
            return False
        self.apikey = content['akey']
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True
        
    def getFileList(self):
        return []
    
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        #indexpage        
        get_upload_info_url = 'http://ifile.it/api-fetch_upload_url.api'
        get_upload_info_page = self.post_request(get_upload_info_url)
        
        print get_upload_info_page
        get_upload_info_page = json.loads(get_upload_info_page)
        if not get_upload_info_page['status'] == 'ok':
            self.fherr.write("Failed to get upload url.")
            return        
        upload_url = get_upload_info_page['upload_url']        
        
        info = "Uploading...%s" % file
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
            
        fileobj = open(file, 'rb')
        fileobj.seek(start_point)  
        
        data = {"akey":self.apikey,
                "Filedata":fileobj}
        
        self.fherr.write(info)
        self.fherr.write("Apikey:{}\r\nUpload_url:{}".format(self.apikey, upload_url))
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_url, \
                                   data, \
                                   cb=callback, \
                                   retry=1, \
                                   setfilename=filename, \
                                   setfilesize=filesize)
        #result
        print result
        content = json.loads(result)
        if content['status'] == 'error':
            self.fherr.write("Get a wrong result after uploaded.")
            self.fherr.write(content['message'])
            return
        
        link = 'http://ifile.it/{ukey}/{name}'.format(**content)
        item = ifiitem(os.path.basename(file), 'file', '', link, filename)
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        return item